#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2021-present pkegg

#Constants
CONSOLE_DEVICE=/dev/console
. /etc/profile

LOG=/tmp/logs/351-elec-upgrade
DIR=$(realpath $(dirname $0))
BAND=$(get_ee_setting updates.type)
ORG=$(get_ee_setting updates.github.org)
if [ "$ORG" == "" ]; then
  ORG="AmberELEC"
fi

REPO=$(get_ee_setting updates.github.repo)
if [ "$REPO" == "" ]; then
  if [ "$BAND" == "prerelease" ] || [ "$BAND" == "beta" ]; then
    REPO=AmberELEC-prerelease
  else
    REPO=AmberELEC
  fi
fi

FORCE=$(get_ee_setting updates.force)
if [ "$FORCE" == "1" ]; then
  FORCE_ARGS="--force-update"
fi

systemctl stop emustation

# Ensure we start emustation back up at end
function cleanup {
  clear > ${CONSOLE_DEVICE}
  systemctl start emustation

}
trap cleanup EXIT

clear > ${CONSOLE_DEVICE}

python3 ${DIR}/get-release.py --band ${BAND} --org ${ORG} --repo ${REPO} --log-level DEBUG --console ${CONSOLE_DEVICE} ${FORCE_ARGS} &> ${LOG}

RETURN_CODE=$?

if [ "${RETURN_CODE}" != "0" ]
then
  exit 1
else
  sync
  reboot
fi